package com.fencing_squad.homo.slice;

import com.alibaba.fastjson.JSONObject;
import com.fencing_squad.homo.ResourceTable;
import com.fencing_squad.homo.list.Offer;
import com.fencing_squad.homo.list.OfferProvider;
import com.fencing_squad.homo.util.CustomComponent;
import com.fencing_squad.homo.util.Data;
import com.fencing_squad.homo.util.Network;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;

import java.util.ArrayList;

public class UserOfferSlice extends AbilitySlice {
    OfferProvider provider;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent((ComponentContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_user_offer_page, null, false));

        initConfig();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void initConfig() {
        ListContainer container = (ListContainer) findComponentById(ResourceTable.Id_userOfferList);
        provider = new OfferProvider(this);
        container.setItemProvider(provider);
        container.setItemClickedListener((listContainer, component, i, l) -> {
            Offer offer = (Offer) provider.getItem(i);
            Intent intent = new Intent();
            intent.setParam("rewardId", offer.getRewardId());
            intent.setParam("isSupervisor", !offer.getGetId().equals(Data.Account.uid));
            present(new SupervisorSlice(), intent);
        });

        Text barTitle = (Text) findComponentById(ResourceTable.Id_barTitle);
        Component barBack = findComponentById(ResourceTable.Id_barBack);
        barTitle.setText("我的悬赏");
        barBack.setClickedListener(component -> {
            terminate();
        });

        Network.get("/user/reward", this::resolve, this::reject);
    }

    private void resolve(JSONObject object) {
        provider.append(Offer.getFromJSONArray(object.getJSONObject("data").getJSONArray("data")));
    }

    private void reject(int code, String message) {
        if(code == 404) {
            CustomComponent.getDialog(this, message, null, null).show();
        }
        else {
            System.out.println(message);
        }
    }

    public static ArrayList<Offer> test() {
        ArrayList<Offer> list = new ArrayList<>();
        for(int i=0; i<10; i++) {
            Offer offer = new Offer();
            offer.setContent("contentttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt" + String.valueOf(i));
            offer.setNickname("nick" + String.valueOf(i));
            offer.setRewardId("123456");
            offer.setStatus("已揭榜");
            list.add(offer);
        }
        return list;
    }
}
